/*
 * Copyright ©2021 su binglun(9085309@qq.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *---------------------------------------------------------------------
 *-                                                                   -
 *-           Website : http://phoenix.sunny360.cn/                   -
 *-                                                                   -
 *---------------------------------------------------------------------
 */
package cn.sunny360.core.service.impl;

import com.sohu.idcenter.IdWorker;
import cn.sunny360.core.service.DeviceService;
import cn.sunny360.core.utils.Container;
import cn.sunny360.core.wrapper.DBWrapper;
import io.vertx.core.*;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Tuple;

import java.util.Arrays;

/**
 * 设备管理服务
 * @author sublun
 *
 */
public class DeviceServiceImpl implements DeviceService {
	
	private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
	private IdWorker idWorker;
	private DBWrapper dbWrapper;

	public DeviceServiceImpl() {
		this.idWorker = Container.getComponent(IdWorker.class);
		this.dbWrapper = Container.getComponent(DBWrapper.class);
		logger.info("[DeviceServiceImpl]已经初始化完毕");
	}

	/**
	 *  返回数据格式：
	 *  {"total":1000,"pages":10,"list":[{},{}]}
	 */
	@Override
	public DeviceServiceImpl getIosDeviceList(String appId, Integer page, Integer rows, Promise<JsonObject> promise) {
		/*//查询全部ios设备
		JsonObject query = new JsonObject()
				.put("apps", new JsonObject().put("$elemMatch", new JsonObject().put("app_id", appId)))
				.put("os", "ios");
		Future<Long> f1 = Future.future();
		mongoClient.count(COLLENCTION_DEVICE, query, f1.completer());
		//分页查询设备列表
		Future<List<JsonObject>> f2 = Future.future();
		//设置查询调节
		FindOptions options = new FindOptions()
				.setSkip((page - 1) * rows)
				.setLimit(rows);
		mongoClient.findWithOptions(COLLENCTION_DEVICE, query, options, f2.completer());
		CompositeFuture.all(f1, f2)
			.setHandler(h->{
				if (h.succeeded()) {
					List<Object> list = h.result().list();
					long total = (long) list.get(0);
					long pages = total / rows;
					if (total % rows > 0) {
						pages++;
					}
					JsonObject jsonObject = new JsonObject()
							.put("total", total)
							.put("pages", pages)
							.put("list", list.get(1));
					handler.handle(Future.succeededFuture(jsonObject));
				} else {
					handler.handle(Future.failedFuture(h.cause()));
				}
			});*/
		return this;
	}

	@Override
	public DeviceServiceImpl getDeviceInfoByToken(String token, Promise<JsonObject> promise) {
		dbWrapper.findOne("select * from ph_device where token = ?", Tuple.of(token))
				.future()
				.onFailure(promise::fail)
				.onSuccess(o->{
					if(!o.isPresent()) {
						promise.fail("此token对应的设备不存在");
					} else {
						JsonObject jsonObject = o.get();
						logger.info("查询到token[" + token + "]对应的设备信息");
						logger.debug("["+token+"]对应的设备信息为：" + jsonObject);
						promise.complete(jsonObject);
					}
				});

		return this;
	}
	
	@Override
	public DeviceServiceImpl saveDeviceInfo(JsonObject device, Promise<String> promise) {
		logger.debug(device);
		//删除设备信息，如果有的话。然后添加一条新的记录
		dbWrapper.executeWithTrans(Arrays.asList(
				new DBWrapper.SQLTuple("delete from ph_device where device_id=?", Tuple.of(device.getString("device_id"))),
				new DBWrapper.SQLTuple("insert into ph_device(" +
						"	device_id," +
						"	device_brand," +
						"	device_type," +
						"	os," +
						"	os_version," +
						"	ios_token," +
						"	app_ver" +
						") values(" +
						"?,?,?,?,?,?,?" +
						")", Tuple.of(
								device.getString("device_id"),
								device.getString("device_brand"),
								device.getString("device_type"),
								device.getString("os"),
								device.getString("os_version"),
								device.getString("ios_token"),
								device.getString("app_ver")
						))
		)).future()
				.onFailure(promise::fail)
				.onSuccess(h->promise.complete("OK"));

		return this;
	}

}
